//
//  RNTPolyvLiveManager.m

//  test
//
//  Created by 李长杰 on 2019/2/14.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "RNTPolyvLiveManager.h"
#import "RNTPolyvLive.h"
#import <PLVLiveAPI/PLVLiveAPI.h>
#import <PLVLiveAPI/PLVLiveConfig.h>
#import <PLVVodSDK/PLVVodSDK.h>
#import <React/RCTBridge.h>
#import <React/RCTUIManager.h>
#import <React/UIView+React.h>

NSString * NSStringFromPolyvLiveWatchRnError(PolyvLiveWatchRnErrorCode code) {
  switch (code) {
    case PolyvLiveWatchRnError_Success:
      return @"成功";
    case PolyvLiveWatchRnError_NoAppId:
      return @"AppId为空";
    case PolyvLiveWatchRnError_NoAppSecret:
      return @"AppSecret为空";
    case PolyvLiveWatchRnError_NoViewerId:
      return @"viewerId为空";
    case PolyvLiveWatchRnError_NoUserId:
      return @"UserId为空";
    case PolyvLiveWatchRnError_NoChannelId:
      return @"ChannelId为空";
    case PolyvLiveWatchRnError_ChannelLoginFailed:
      return @"频道加载失败";
    default:
      return @"";
  }
}

NSString * NSStringFromPolyvVodRnError(PolyvVodConfigRnErrorCode code) {
  switch (code) {
    case PolyvVodRnError_Success:
      return @"成功";
    case PolyvVodRnError_NoVodKey:
      return @"vodKey为空";
    case PolyvVodRnError_NoDecodeKey:
      return @"decodeKey为空";
    case PolyvVodRnError_NoDecodeIv:
      return @"decodeIv为空";
    case PolyvVodRnError_NoViewerId:
      return @"viewerId为空";
    default:
      return @"";
  }
}

@interface RNTPolyvLiveManager ()

@end

@implementation RNTPolyvLiveManager
{
  /* Required to publish events */
  RNTPolyvLive *rntView;
  BOOL fullscreen;
  BOOL showdanmu;
  NSTimer *_liveStatusTimer;
}

RCT_EXPORT_MODULE()
RCT_EXPORT_VIEW_PROPERTY(canorientation, BOOL);
RCT_EXPORT_VIEW_PROPERTY(paused, BOOL);
RCT_EXPORT_VIEW_PROPERTY(fullscreen, BOOL);
RCT_EXPORT_VIEW_PROPERTY(showdanmu, BOOL);
RCT_EXPORT_VIEW_PROPERTY(danmumsg, NSString *);
RCT_EXPORT_VIEW_PROPERTY(goback, void);
RCT_EXPORT_VIEW_PROPERTY(onPlayLiveEvent, RCTBubblingEventBlock);
@synthesize bridge = _bridge;

- (UIView *)view
{
  if (rntView == nil) {
    rntView = [[RNTPolyvLive alloc] initWithEventDispatcher:self.bridge.eventDispatcher];
  }
  return rntView;
}
- (dispatch_queue_t)methodQueue
{
  return dispatch_get_main_queue();
}
// 参数 appId (必填)
// 参数 appSecret (必填)
// 参数 viewerId（必填）
// 参数 nickName（选填）
// 参数 avatar（选填）
// polyvSetting
// {
//    appId
//    appSecret
//    encryptionKey
//    encryptionVector
//    sdkString
//    userId
// }
RCT_EXPORT_METHOD(initPolyLive:(NSString *)startTime
                  channelId:(NSString *)channelId
                  vidWarmVideo:(NSString *)vidWarmVideo
                  polyvSetting:(NSDictionary *)polyvSetting
                  findEventsWithResolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject
                  )
{
  if (rntView == nil) {
    rntView = [[RNTPolyvLive alloc] initWithEventDispatcher:self.bridge.eventDispatcher];
  }
  if (vidWarmVideo && vidWarmVideo.length > 0) {
    NSError *error = nil;
    NSString *vodKey = polyvSetting[@"sdkString"];
    NSString *decodeKey = polyvSetting[@"encryptionKey"];
    NSString *decodeIv = polyvSetting[@"encryptionVector"];
    [PLVVodSettings settingsWithConfigString:vodKey key:decodeKey iv:decodeIv error:&error];
    self->rntView.vidWarmVideo = vidWarmVideo;
  }
  if (channelId && channelId.length > 0) {
    NSString *appId = polyvSetting[@"appId"];
    NSString *appSecret = polyvSetting[@"appSecret"];
    NSString *userId = polyvSetting[@"userId"];
    [PLVLiveConfig liveConfigWithAppId:appId appSecret:appSecret];
    [PLVLiveConfig setViewLogParam:@"" param2:nil param4:nil param5:nil];
    [PLVLiveConfig setLogLevel:k_PLV_LIVE_LOG_ERROR];
    __weak typeof(self)weakSelf = self;
    [PLVLiveAPI loadChannelInfoRepeatedlyWithUserId:userId channelId:channelId.integerValue completion:^(PLVLiveChannel *channel) {
      __strong typeof(weakSelf) strongSelf = weakSelf;
      if (strongSelf->rntView) {
        strongSelf->rntView.startTime = startTime;
        strongSelf->rntView.userId = userId;
        strongSelf->rntView.liveChannel = channel;
        [strongSelf updateLiveChanel];
        resolve(@"request channel succcess");
      }
    } failure:^(PLVLiveErrorCode errorCode, NSString *description) {
      __strong typeof(weakSelf) strongSelf = weakSelf;
      [strongSelf updateLiveChanel];
      NSString *errorDesc = NSStringFromPolyvLiveWatchRnError(PolyvLiveWatchRnError_ChannelLoginFailed);
      NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:PolyvLiveWatchRnError_ChannelLoginFailed userInfo:@{NSLocalizedDescriptionKey:errorDesc}];
      RCTLog(@"%@", errorDesc);
      reject([@(PolyvLiveWatchRnError_ChannelLoginFailed) stringValue], errorDesc, error);
    }];
  } else {
    [self updateLiveChanel];
    resolve(@"no channel");
  }
}
- (void)updateLiveChanel{
  [self->rntView updateLiveChanel];
}

// 参数 vodKey (必填)
// 参数 decodeKey (必填)
// 参数 decodeIv（必填）
// 参数 viewerId（必填）
// 参数 nickName（选填）
RCT_EXPORT_METHOD(initPolyVod:(NSString *)vodKey
                  decodeKey:(NSString *)decodeKey
                  decodeIv:(NSString *)decodeIv
                  viewerId:(NSString *)viewerId
                  nickName:(NSString *)nickName
                  vid:(NSString *)vid
                  findEventsWithResolver:(RCTPromiseResolveBlock)resolve
                  rejecter:(RCTPromiseRejectBlock)reject
                  )
{
  RCTLog(@"config() - %@ 、 %@ 、 %@", vodKey, decodeKey, decodeIv);
  
  NSError *error = nil;
  PLVVodSettings *settings = [PLVVodSettings settingsWithConfigString:vodKey key:decodeKey iv:decodeIv error:&error];
  NSString *readToken = settings.readtoken;
  
  settings.logLevel = PLVVodLogLevelAll;
  
  settings.viewerId = viewerId;
  settings.viewerName = nickName ? nickName : @"游客";
  
  if (rntView) {
    //    rntView.vid=vid;
  }
  NSDictionary *dic = @{ @"code": @(PolyvVodRnError_Success), @"token":readToken, @"isSign":@(NO) };
  
  resolve(dic);
  
}
RCT_EXPORT_METHOD(freePlayer)
{
  if ([NSThread isMainThread]) {
     NSLog(@"isMainThread");
   }
  if (rntView) {
    [rntView freePlayer];
    rntView = nil;
  }
}
@end

